from django.contrib.auth import *
from django.contrib.auth.models import *
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models.query_utils import Q
from django.http import *
from django.shortcuts import *
from django.views.decorators.http import require_http_methods, require_POST, \
    require_GET
import json

from trp.models import *
from utils.JsonResponse import JsonResponse, JsonResponseBadrequest
from utils.decorators import *
from utils.utils import *
from website.settings import LOGGER as logger

@login_required
def main(request):
    return render_to_response("trp/paylog.html",{'user' : request.user, 'page' : 'organization'})
@login_required_ajax
def get_paylogs(request):
    result = {}
    dataArr = []
    param = json.loads(request.body)
    searchTxt = param.get("searchTxt", "")
    searchTxt = searchTxt.strip()
    org_id = param.get("org_id")or -1
    pageSize = param.get("pageSize", 20)
    pageNo = param.get("pageNo", 1)
    
    order = param.get("order","desc")
    
    try :
        pageSize = int(pageSize)
        pageNo = int(pageNo)
    except Exception,e:
        logger.exception(e)
        return HttpResponseBadRequest(param)
    org = Organization.objects.get(pk=int(org_id))
    qset = PayLog.objects.select_related("organization","account","account__user").filter(organization=org).order_by("-id")
    if searchTxt :
        qset = qset.filter(Q(organization__name__icontains=searchTxt))
    
    paginator = Paginator(qset, pageSize)
    try:
        pageObj = paginator.page(pageNo)
    except PageNotAnInteger:
        pageObj = paginator.page(1)
    except EmptyPage:
        pageObj = paginator.page(paginator.num_pages)
    
    for ele in pageObj.object_list:
        ele_n = {}
        ele_n["id"]=ele.id
        ele_n["organization"] = ele.organization and ele.organization.name
        ele_n["in_balance"] = ele.in_balance
        ele_n["out_balance"] = ele.out_balance
        ele_n["ally_balance"] = ele.ally_balance
        ele_n["time"] = ele.time and ele.time.strftime("%Y-%m-%d %H:%M:%S")
        ele_n["charger"] = ele.account.user.username
        dataArr.append(ele_n)
    result["pageNo"] = pageNo
    result["pageSize"] = pageSize
    result["totalCount"] = paginator.count
    result["bodyData"] = dataArr
    return JsonResponse(result)